<template>
  <el-card class="container">
    <div class="title">{{ $t('msg.chart.bmapChartTitle') }}</div>
    <div ref="target" class="box"></div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getChartMap } from '@/api/chart'
import 'echarts/extension/bmap/bmap.js'
import * as echarts from 'echarts'
import { useI18n } from 'vue-i18n'

const i18n = useI18n()

// 获取数据
const mapData = ref({})
const getMapData = async () => {
  const res = await getChartMap()
  mapData.value = res
  renderBMap()
}
getMapData()

// 数据转换的方法
const converData = (data) => {
  const res = []
  data.forEach((item) => {
    const geoCoord = mapData.value.geoCoordMap[item.name]
    if (geoCoord) {
      res.push({
        name: item.name,
        value: [...geoCoord, item.value]
      })
    }
  })
  return res
}

// 地图绘制
const target = ref(null)
let myChart
onMounted(() => {
  myChart = echarts.init(target.value)
})

const renderBMap = () => {
  const options = {
    tooltip: {
      trigger: 'item'
    },
    bmap: {
      // 中心点
      center: [104.114129, 37.550339],
      // 缩放级别
      zoom: 5,
      // 是否可拖动
      roam: true
    },
    series: [
      {
        name: `营收 ${i18n.t('msg.chart.unit')}`,
        type: 'scatter',
        coordinateSystem: 'bmap',
        data: converData(mapData.value.data),
        symbolSize: function (val) {
          return val[2] / 10
        },
        encode: {
          value: 2
        },
        emphasis: {
          label: {
            show: true
          }
        },
        color: '#15803D'
      },
      {
        name: `营收 TOP 5 （${i18n.t('msg.chart.unit')}）`,
        type: 'effectScatter',
        coordinateSystem: 'bmap',
        data: converData(
          mapData.value.data.sort((a, b) => b.value - a.value)
        ).slice(0, 6),
        symbolSize: function (val) {
          return val[2] / 10
        },
        encode: {
          value: 2
        },
        rippleEffect: {
          brushType: 'stroke'
        },
        label: {
          formatter: '{b}',
          position: 'right',
          show: true
        },
        zlevel: 2,
        color: '#166534'
      }
    ]
  }
  myChart.setOption(options)
}
</script>

<style scoped lang="scss">
.container {
  position: relative;
  .title {
    position: absolute;
    top: 28px;
    margin-left: 50%;
    transform: translateX(-50%);
    color: #333;
    font-size: 22px;
    font-weight: bold;
    z-index: 9;
  }
  .box {
    height: 462px;
  }
}
</style>
